#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
故障管理系统前端服务启动脚本
"""

import http.server
import socketserver
import os
import webbrowser
import threading
import time

# 设置前端目录
FRONTEND_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "frontend")
PORT = 8081  # 修改端口为8081

class CORSRequestHandler(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', '*')
        super().end_headers()

    def do_OPTIONS(self):
        self.send_response(200)
        self.end_headers()

def start_server():
    os.chdir(FRONTEND_DIR)
    
    with socketserver.TCPServer(("", PORT), CORSRequestHandler) as httpd:
        print(f"前端服务启动成功!")
        print(f"访问地址: http://localhost:{PORT}/index.html")
        print("按 Ctrl+C 停止服务")
        
        # 在新线程中打开浏览器
        def open_browser():
            time.sleep(2)  # 等待服务器启动
            webbrowser.open(f"http://localhost:{PORT}/index.html")
        
        threading.Thread(target=open_browser, daemon=True).start()
        
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\n服务已停止")

if __name__ == "__main__":
    start_server()